package peer;


import java.util.HashMap;

public class PeerMessageControler {
	
	private static PeerMessageControler instance;
	
	private HashMap<Integer, Record> map;

	private AritmeticProgressionNumberGenerator numGen;
	
	private PeerMessageControler() {
		map = new HashMap<Integer, PeerMessageControler.Record>();
		numGen = new AritmeticProgressionNumberGenerator();
	}
	
	public static PeerMessageControler getInstance() {
		if (instance == null) {
			instance = new PeerMessageControler();
		}
		return instance;
	}

	public synchronized void receiveAck(int sequenceNumber) {
		Object retur = map.remove(new Integer(sequenceNumber));
		if(retur == null)
			System.out.println("! Nao encontrado Record associado ao sequenceNumber= "+ sequenceNumber);
		else System.out.println("! Encontrado Record.  sequenceNumber= "+ sequenceNumber);
	}
	
	public synchronized void recordData(int seqNum, byte[] array){
		map.put(new Integer(seqNum), new Record(System.currentTimeMillis(), array));
	}
	
	public synchronized int generateSeqNum(){
		int number = numGen.generateNumber();
		//System.out.println("## Numero gerado: " + number);
		return number;
	}
		
	
	private class Record{
		private long timestamp;
		private byte[] array;
		
		public Record(long timestamp, byte[] array) {
			this.timestamp = timestamp;
			this.array = array;
		}
		
		public long getTimestamp() {
			return timestamp;
		}

		public void setTimestamp(long timestamp) {
			this.timestamp = timestamp;
		}

		public byte[] getArray() {
			return array;
		}

		public void setArray(byte[] array) {
			this.array = array;
		}
		
		@Override
		public String toString() {
			return "@Record[ timestamp= "+ timestamp+ " , array= " + array + " ]";   
		}
	}
	
	private class AritmeticProgressionNumberGenerator {
	    static final int A = 2;//era 1
	    static final int D = 2;
	    int count= 1;

	    public int generateNumber() {
	    	return (A + ((count++ - 1)*D)); 
	    }
	}
	
	

}
